local bRunning = true
local tCommandHistory = {}
local tEnv = {
	["exit"] = function()
		bRunning = false
	end,
	["_echo"] = function( ... )
	    return ...
	end,
}

if not security.getSU() then
 exception.throw("RestrictedOpsException")
 return
end

setmetatable( tEnv, { __index = _ENV } )

local label = os.getComputerLabel() or os.getComputerID()

term.setTextColour( colours.yellow )
print( os.version() )
print( "Manual Lua code interpreter. Call exit() to abort." )
term.setTextColour( colours.white )

while bRunning do
	if security.getActiveUserStatus() then
	    term.setTextColour( colours.lime )
	else
	    term.setTextColour( colours.orange )
	end
	write( _activeUser )
	term.setTextColour( colours.lightGrey )
	write( "@" )
	term.setTextColour( colours.lightBlue )
	write( label )
	term.setTextColour( colours.lightGrey )
	write( "/" )
	term.setTextColour( colours.lightBlue )
	write( shell.dir() )
	if security.getActiveUserStatus() then
	    term.setTextColour( colours.lime )
	else
	    term.setTextColour( colours.orange )
	end
	write( " % " )

	term.setTextColour( colours.white )

	local s = read( nil, tCommandHistory, function( sLine )
	    local nStartPos = string.find( sLine, "[a-zA-Z0-9_%.]+$" )
	    if nStartPos then
	        sLine = string.sub( sLine, nStartPos )
	    end
	    if #sLine > 0 then
            return textutils.complete( sLine, tEnv )
        end
        return nil
	end )
	term.setTextColour( colours.lightGrey )
	table.insert( tCommandHistory, s )
	
	local nForcePrint = 0
	local func, e = load( s, "lua", "t", tEnv )
	local func2, e2 = load( "return _echo("..s..");", "lua", "t", tEnv )
	if not func then
		if func2 then
			func = func2
			e = nil
			nForcePrint = 1
		end
	else
		if func2 then
			func = func2
		end
	end
	
	if func then
        local tResults = { pcall( func ) }
        if tResults[1] then
        	local n = 1
        	while (tResults[n + 1] ~= nil) or (n <= nForcePrint) do
        	    local value = tResults[ n + 1 ]
        	    if type( value ) == "table" then
            	    local ok, serialised = pcall( textutils.serialise, value )
            	    if ok then
            	        print( serialised )
            	    else
            	        print( tostring( value ) )
            	    end
            	else
            	    print( tostring( value ) )
            	end
        		n = n + 1
        	end
        else
        	printError( tResults[2] )
        end
    else
    	printError( e )
    end
    
end